$(function () {
    let buttonGroup = [
        {
            id: 'btn_add',
            size: 'small',
            text: '新增付款',
            iconCls: 'icon-add',
            plain: true,
            onClick: btn_add_payment
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_print',
            size: 'small',
            text: '打印',
            iconCls: 'icon-print',
            plain: true,
            onClick: btn_print
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    bindEnterEvents();
    grid_1();
    let kGrid = $('#v_grid').data('kendoGrid');
    var options = kGrid.getOptions();
    if (options.columns.length > 0)
        initCombobox(options)
})

//  财务管理-外发对账
function grid_1() {
    let SUFFIX = "_a";
    let company_name = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "productOutwardOrder/report/account",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    processName: $('#contactCompanyId').combobox('getValue'),
                    mode: $('#state').switchbutton('options').checked ? 0 : 1
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    order_date: {type: "date"},
                    box_amount: {type: "number"},
                    material_input_kilo: {type: "number"},
                    greyfabric_input_kilo: {type: "number"},
                    process_money: {type: "number"},
                    pay: {type: "number"},
                    amount: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "box_amount", aggregate: "sum"},
            {field: "material_input_kilo", aggregate: "sum"},
            {field: "greyfabric_input_kilo", aggregate: "sum"},
            {field: "process_money", aggregate: "sum"},
            {field: "pay", aggregate: "sum"},
            {field: "amount", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            company_name.data(unique(data, 'company_name'));

        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "order_date",
            title: '日期',
            width: 85,
            format: "{0: MM-dd}",
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: "is_send_directly",
            title: '直发',
            width: 93,
            template: item => item['is_send_directly'] == '是' ? `<input type="checkbox" checked onclick="return false;">` : '',
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "material_spec",
            title: '原料规格',
            filterable: false,
            width: 67,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: "process_company",
            title: '加工户',
            width: 67,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: "bill_type_name",
            title: '单据类型',
            width: 67,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: "supplier_name",
            title: '原料商',
            width: 88,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: "batch_num",
            title: '批次号',
            width: 88,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: 'box_amount',
            title: '件数',
            width: 80,
            template: item => {
                return item.box_amount ? parseFloat(item.box_amount).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'material_input_kilo',
            title: '原料重量',
            width: 80,
            template: item => {
                return item.material_input_kilo ? parseFloat(item.material_input_kilo).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "product_name",
            title: '品名',
            width: 88,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: "plan_code",
            title: '计划单号',
            width: 88,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        {
            field: "greyfabric_spec",
            title: '坯布规格',
            width: 88,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'}
        },
        /*{
            field: "material_spec2",
            title: '原料规格',
            width: 88,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes:{'class':'kendo-custum-char'}
        },*/
        {
            field: 'amount',
            title: '匹数/件数',
            width: 80,
            template: item => {
                return item.amount ? parseFloat(item.amount).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'greyfabric_input_kilo',
            title: '白坯重量',
            width: 80,
            template: item => {
                return item.greyfabric_input_kilo ? parseFloat(item.greyfabric_input_kilo).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'process_cost',
            title: '加工单价',
            width: 80,
            template: item => {
                return item.process_cost ? parseFloat(item.process_cost).toFixed(2) : '';
            },
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'process_money',
            title: '加工费',
            width: 80,
            template: item => {
                return item.process_money ? parseFloat(item.process_money).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'pay',
            title: '付款',
            width: 80,
            template: item => {
                return item.pay ? parseFloat(item.pay).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "consignee",
            title: '送货地址',
            width: 88,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'}
        },
    ];
    let grid = $("#v_grid").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "加工户对账单.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
                let dataItem = kGrid.dataItem($(this));
                let type = dataItem['mark_finished'];
                if (type) {
                    $(this).removeClass('k-alt');
                    $(this).addClass('kendo-background-color-yellow');
                }
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('click', 'tr', function (e) {
    })
    grid.on('dblclick', 'tr', function (e) {
        btn_modify_payment();
    });
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
    });
}

function btn_add_payment() {
    let columns = [
        {
            field: 'processName',
            title: '加工户',
            editor: {
                type: 'combobox', options: {
                    url: 'processCompany/listQuery',
                    method: 'GET', queryParams: {state: 1, isSelected: false},
                    textField: 'companyName', valueField: 'companyName',
                    panelHeight: 200,
                    required: true,
                    onLoadSuccess: function () {
                        $(this).combobox('options').limitToList = true;
                        if (!$(this).combobox('getValue')) {
                            let loadData = $(this).combobox('getData') || [];
                            let opts = $(this).combobox('options');
                            if (loadData.length > 0) {
                                if ($('#contactCompanyId').combobox('getValue')) {
                                    $(this).combobox('setValue', $('#contactCompanyId').combobox('getValue'));
                                } else {
                                    $(this).combobox('setValue', loadData[0][opts.valueField]);
                                }
                            }
                        }
                    }
                }
            }
        },
        {
            field: 'billDate',
            title: '日期',
            editor: {type: 'datebox', options: {required: true, value: getCurrentDate()}}
        },
        {
            field: 'billtype',
            title: '项目',
            editor: {
                type: 'combobox', options: {
                    required: true,
                    data: [{value: '付款'}, {value: '付款调整'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto',
                    onChange: function (newVal, oldVal) {
                        if (newVal == '付款调整') {
                            $('#collectiontypeInput').combobox('clear');
                            $('#collectiontypeInput').combobox('disable');
                        } else {
                            $('#collectiontypeInput').combobox('enable');
                        }
                    }
                }
            }
        },
        {
            field: 'money',
            title: '金额',
            editor: {type: 'numberbox', options: {precision: 2, required: true,}}
        },
        {
            field: 'payableType',
            id: 'collectiontypeInput',
            title: '付款类型',
            editor: {
                type: 'combobox', options: {
                    data: [{value: '转账'}, {value: '承兑'}, {value: '现金'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto'
                }
            }
        },
        {
            field: 'billmemo',
            title: '备注',
            editor: {type: 'textbox', options: {multiline: true, height: 100}}
        }
    ];
    let loadData = {};
    openDialogByOpts({
        loadData: loadData,
        columns: columns,
        height: 380,
        width: 330,
        mode: '新增付款',
        buttons: [{
            text: '保存', iconCls: 'icon-save', handler: e => {
                let dialog = $('.form-dialog-edit');
                if (!$(dialog.find('form')).form('validate')) {
                    return;
                }
                let param = $(dialog.find('form')).serializeObject();
                let url = 'processAccountPayable/insertSelective';
                //  修改
                $.messager.progress({
                    title: '',
                    msg: '请稍等...',
                    interval: 5000
                });
                $.ajax({
                    url: url,
                    type: 'POST',
                    dataType: 'json',
                    data: param,
                    success: function (data) {
                        if (data.success) {
                            btn_search();
                            $.formDialog.close();
                            $.messager.show({title: '提示', msg: data.message});
                        } else {
                            $.messager.alert('提示', data.message, 'warning');
                        }
                    },
                    complete: function () {
                        $.messager.progress('close');
                    }
                })
            }
        }, {
            text: '取消', iconCls: 'icon-cancel', handler: e => {
                $.formDialog.close();
            }
        }]
    });
}

function btn_modify_payment() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem == undefined || !dataItem['id']) {
        $.messager.alert('提示', '请选中付款或付款调整', 'warning');
        return;
    }
    let columns = [
        {
            field: 'id',
            title: '编号',
        },
        {
            field: 'processName',
            title: '加工户',
            editor: {
                type: 'combobox', options: {
                    url: 'processCompany/listQuery',
                    method: 'GET', queryParams: {state: 1, isSelected: false},
                    textField: 'companyName', valueField: 'companyName',
                    panelHeight: 200,
                    required: true,
                    onLoadSuccess: function () {
                        $(this).combobox('options').limitToList = true;
                    }
                }
            }
        },
        {
            field: 'billDate',
            title: '日期',
            editor: {type: 'datebox', options: {required: true, value: getCurrentDate()}}
        },
        {
            field: 'billtype',
            title: '项目',
            editor: {
                type: 'combobox', options: {
                    required: true,
                    data: [{value: '付款'}, {value: '付款调整'}],
                    textField: 'value',
                    valueField: 'value',
                    panelHeight: 'auto',
                    limitToList: true,
                    onChange: function (newVal, oldVal) {
                        if (newVal == '付款调整') {
                            $('#collectiontypeInput').combobox('clear');
                            $('#collectiontypeInput').combobox('disable');
                        } else {
                            $('#collectiontypeInput').combobox('enable');
                        }
                    }
                }
            }
        },
        {
            field: 'money',
            title: '金额',
            editor: {type: 'numberbox', options: {precision: 2, required: true,}}
        },
        {
            field: 'payableType',
            id: 'collectiontypeInput',
            title: '付款类型',
            editor: {
                type: 'combobox', options: {
                    data: [{value: '转账'}, {value: '承兑'}, {value: '现金'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto'
                }
            }
        },
        {
            field: 'billmemo',
            title: '备注',
            editor: {type: 'textbox', options: {multiline: true, height: 100}}
        }
    ];
    $.ajax({
        url: `processAccountPayable/queryByPk/${dataItem.id}`,
        type: 'GET',
        dataType: 'json',
    }).then(data => {
        openDialogByOpts({
            loadData: data,
            columns: columns,
            height: 380,
            width: 330,
            mode: '修改付款',
            buttons: [
                {
                    text: '删除付款', iconCls: 'icon-remove', handler: e => {
                        $.messager.confirm('提示', '是否确定删除？删除后不可恢复!', function (r) {
                            if (r) {
                                $.messager.progress({
                                    title: '',
                                    msg: '请稍等...',
                                    interval: 5000
                                });
                                let dialog = $('.form-dialog-edit');
                                let url = 'processAccountPayable/deleteByPk';
                                let param = $(dialog.find('form')).serializeObject();
                                $.ajax({
                                    url: url,
                                    type: 'POST',
                                    dataType: 'json',
                                    data: {id: param['id'] || 0},
                                    success: function (data) {
                                        if (data.success) {
                                            btn_search();
                                            $.formDialog.close();
                                            $.messager.show({title: '提示', msg: data.message});
                                        } else {
                                            $.messager.alert('提示', data.message, 'warning');
                                        }
                                    },
                                    complete: function () {
                                        $.messager.progress('close');
                                    }
                                })
                            }
                        })
                    }
                }, {
                    text: '保存', iconCls: 'icon-save', handler: e => {
                        let dialog = $('.form-dialog-edit');
                        if (!$(dialog.find('form')).form('validate')) {
                            return;
                        }
                        let param = $(dialog.find('form')).serializeObject();
                        let url = 'processAccountPayable/updateSelective';
                        //  修改
                        $.messager.progress({
                            title: '',
                            msg: '请稍等...',
                            interval: 5000
                        });
                        $.ajax({
                            url: url,
                            type: 'POST',
                            dataType: 'json',
                            data: param,
                            success: function (data) {
                                if (data.success) {
                                    btn_search();
                                    $.formDialog.close();
                                    $.messager.show({title: '提示', msg: data.message});
                                } else {
                                    $.messager.alert('提示', data.message, 'warning');
                                }
                            },
                            complete: function () {
                                $.messager.progress('close');
                            }
                        })
                    }
                }, {
                    text: '取消', iconCls: 'icon-cancel', handler: e => {
                        $.formDialog.close();
                    }
                }],
            onOpen: function () {
                setTimeout(function () {
                    $('.form-dialog-edit').dialog('panel').find('.l-btn').eq(0).css({float: 'left'});
                }, 0)
            }
        });
    }, () => {
        $.messager.alert('提示', '无法连接服务器!', 'error');
    })
}

function openDialogByOpts(opts) {
    $.formDialog.open(opts);
}

function btn_cancel_filter() {
    $('#v_grid').data('kendoGrid').dataSource.filter({});
}

function btn_search() {
    $('#v_grid').data('kendoGrid').dataSource.read({
        start: $('#start').datebox('getValue'),
        end: $('#end').datebox('getValue'),
        processName: $('#contactCompanyId').combobox('getValue'),
        mode: $('#state').switchbutton('options').checked ? 0 : 1
        // textField: $('#column').combobox('getValue'),
        // valueField: $('#value').textbox('getValue'),
    })
}

//  打印
function btn_print() {
    let kGrid = $("#v_grid").data("kendoGrid");
    let selections = kGrid.select();
    if (selections.length <= 0) {
        $.messager.alert('提示', '请选中计划!', 'warning')
        return;
    }
    let arr = new Set();
    $(selections).each(function () {
        arr.add(kGrid.dataItem(this)['id']);
    })
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            arr.forEach(item => {
                reportlets.push({
                    reportlet: data.data + '/加工户对账单.cpt',
                    id: item,
                    database: data.data
                })
            });
            window.parent.FR.doURLPDFPrint({
                url: $(window.parent.document.body).data('report_url'),
                isPopUp: false,
                data: {
                    reportlets: reportlets
                }
            })
        }
    }, 'json');
}

function btn_open_column_list() {
    let kendoGridID = '#v_grid';
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列'" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

function btn_export_excel() {
    $('#v_grid').data('kendoGrid').saveAsExcel();
}

function btn_close() {
    window.parent.closeTab();
}

function stateChange(checked) {
    setState(checked);
    btn_search();
}

function setState(state) {
    if (state) {
        $('#start').datebox('enable');
        $('#end').datebox('enable');
    } else {
        $('#start').datebox('disable');
        $('#end').datebox('disable');
    }
}

//选中事件
function initCombobox(options) {
    var columns = options.columns;
    columns.splice(0, 1);
    $('#column').combobox({
        valueField: 'field',
        textField: 'title',
        data: columns,
        editable: false
    })
}